package com.leetcode.p400;

import com.bean.ListNode;
import com.utils.DataUtils;

import java.util.Stack;

public class Test445 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode();

        Stack<Integer> s1 = new Stack<>();
        Stack<Integer> s2 = new Stack<>();

        while (l1 != null) {
            s1.push(l1.val);
            l1 = l1.next;
        }

        while (l2 != null) {
            s2.push(l2.val);
            l2 = l2.next;
        }

        int carry = 0;

        while (!s1.empty() || !s2.empty() || carry != 0) {
            int d1 = s1.empty() ? 0 : s1.pop();
            int d2 = s2.empty() ? 0 : s2.pop();

            int sum = d1 + d2 + carry;

            if (sum >= 10) {
                carry = 1;
            } else {
                carry = 0;
            }

            ListNode node = new ListNode(sum % 10);
            node.next = head.next;
            head.next = node;
        }

        return head.next;
    }

    public static void main(String[] args) {
        Test445 test = new Test445();
        ListNode l1 = DataUtils.getListNode(new int[]{7, 2, 4, 3});
        ListNode l2 = DataUtils.getListNode(new int[]{5, 6, 4});
//        ListNode l1 = DataUtils.getListNode(new int[]{2, 4, 3});
//        ListNode l2 = DataUtils.getListNode(new int[]{5, 6, 2});
        DataUtils.printListNode(test.addTwoNumbers(l1, l2));
    }
}
